/**
 * SceneLaunch
 * a57633056a
 * Sat Jul 29 2023 01:03:25 GMT+0800 (中国标准时间)
 * SceneLaunch.ts
 * SceneLaunch
 * db://assets/script/game/scene/SceneLaunch.ts
 * https://docs.cocos.com/creator/3.7/manual/zh/
 */
import * as cc from 'cc';
import { GlobalConfig } from '../../GlobalConfig';
import BaseComponent from '../../framework/components/BaseComponent';
import { Loger } from '../../framework/loger/Loger';
import SceneMgr from '../../framework/scene/SceneMgr';
import LabelUtils from '../../framework/utils/LabelUtils';
import { ResUtils } from '../../framework/utils/ResUtils';
import SpriteUtils from '../../framework/utils/SpriteUtils';
import { WxUtils } from '../../framework/wx/WxUtils';
import ModelDebug from '../mvc/debug/model/ModelDebug';
import ModelLogin from '../mvc/login/model/ModelLogin';
import { CompositeDisposable } from '../../framework/event/EventKit';
import GameDataCenter from '../../GameDataCenter';
const { ccclass, property, menu } = cc._decorator;

/**需要预加载的AssetBudle */
const PreloadBundles = [
    "resources",
]
/**需要预加载的主界面 */
const PreloadRes = ["game/prefab/mvc/demo_main/MainDemo"]
@ccclass('SceneLaunch')
@menu('扩展组件/SceneLaunch')
export class SceneLaunch extends BaseComponent {
    public readonly nextScene:string = "main";
    @property({ type: cc.Sprite, tooltip: "进度条" })
    bar: cc.Sprite = null;
    @property({ type: cc.Node, tooltip: "开发节点" })
    nodeDev: cc.Node = null;
    @property({ type: cc.Node, tooltip: "登录" })
    btnLogin: cc.Node = null;
    @property({ type: cc.EditBox, tooltip: "id输入框" })
    edbId: cc.EditBox = null;
    @property({ type: cc.Label, tooltip: "id输入框" })
    txtProg: cc.Label = null;


    private curProg:number = 0;
    start() {
        this.initDataCenter();
        this.initClick();
        this.nodeDev.active = false;
        this.beginLoading()
        this.curProg = 0;
    }

    initDataCenter() {
        GameDataCenter.initModels();
    }

    showDev(isShow: boolean) {
        this.nodeDev.active = isShow;
        if (isShow) {
            const model: ModelLogin = ModelLogin.getInstance() as ModelLogin;
            this.edbId.string = model.getTestOpenId();
        }
    }

    initClick() {
        this.setClickListener(this.btnLogin, () => {
            this.onClickLogin(this.edbId.string)
        })
    }

    progressTo(rate: number,duration:number) {
        if (this.curProg < rate) {
            this.curProg = rate;
            LabelUtils.updatenNumberAnim(this.txtProg, duration, this.curProg * 100, Math.floor(rate * 100),null,'%',0)
            return SpriteUtils.spriteFiledUpTo(this.bar, rate, duration)
        }
    }

    async preloadBundles(){
        for (let index = 0; index < PreloadBundles.length; index++) {
            const bundleName = PreloadBundles[index];
            await ResUtils.loadBundle(bundleName);
            this.progressTo(index/ PreloadBundles.length,0.2);
        }
        await ResUtils.preloadRes(PreloadRes, cc.Prefab,"resources")
        return;
    }

    preloadScene(id?: string, onLaunched?: cc.Director.OnSceneLaunched) {
        let preLoadPromise = new Promise<void>(resolve => {
            cc.director.preloadScene(this.nextScene,
                (completedCount, totalCount, item) => {
                    Loger.log(completedCount, totalCount, item)
                    // this.progressTo(completedCount / totalCount);
                },
                (error: any) => {
                    if (error) {
                        Loger.log("场景预加载失败:", error)
                    }
                    resolve()
                })
        })
        const model: ModelLogin = ModelLogin.getInstance() as ModelLogin;
        Promise.all([preLoadPromise, model.loadConfig(), this.preloadBundles()]).then(() => {
            return Promise.all([
                this.progressTo(1,0.5), 
                // model.loginServer(id)
            ])
        }).then(()=>{
            Loger.log("切换nextScene");
            SceneMgr.getInstance().changeScene(this.nextScene, onLaunched);
        })
        .catch((res) => {
            Loger.log("场景初始化异常")
        })
    }

    

    onClickLogin(id: string) {
        if (!id) {
            Loger.log("请输入id")
            return;
        }
        this.preloadScene(id, () => {
            const model: ModelLogin = ModelLogin.getInstance() as ModelLogin;
            model.setTestOpenId(id);
            model.openNext();

            //debug模式下,显示GM工具
            if (GlobalConfig.showDebugBox || cc.sys.platform == cc.sys.Platform.DESKTOP_BROWSER) {
                let modelDebug = ModelDebug.getInstance() as ModelDebug;
                modelDebug.tryEnter();
            }
        })
    }

    beginLoading() {
        if (WxUtils.isWx()) {
            this.preloadScene(null, () => {
                const model: ModelLogin = ModelLogin.getInstance() as ModelLogin;
                model.openNext();

            })
        } else {
            this.showDev(true);
        }
    }
}